package com.project.study.farming.common.login;

import com.project.study.farming.common.constant.Constant;
import com.project.study.farming.common.entity.po.UserPo;
import com.project.study.farming.common.exception.ServiceException;
import com.project.study.farming.common.utils.BeanMapper;
import com.project.study.farming.common.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 登陆注册
 * @since 2020-04-12
 */
@Controller
@RequestMapping("user")
@Transactional
public class LoginController {

    @Autowired
    private BeanMapper beanMapper;

    @PostConstruct
    public void reg(){
        UserPo po = new UserPo();
        String username = "admin";
        UserPo user = this.beanMapper.selectOne(UserPo.class, String.format("login_id = '%s'", username));
        if(Objects.isNull(user)){
            po.setLoginId(username);
            po.setIsVip("101001");
            po.setUsername(Constant.NEW_USER.getMessage());
            po.setPassword(CommonUtil.encryptStr(Constant.INIT_PASSWORD.getMessage()));
            po.setRealPassword(Constant.INIT_PASSWORD.getMessage());
            po.setCreateTime(LocalDateTime.now());
            po.setCreateBy("admin");
            beanMapper.insert(po);
        }
    }

    @GetMapping("login")
    public String login(UserPo user){
        String loginId = user.getLoginId(), password = user.getPassword();
        UserPo po = this.beanMapper.selectOne(UserPo.class, String.format("login_id = '%s'", loginId));
        if(Objects.isNull(po)){
            throw new ServiceException(String.format("您输入的账号：%s不存在！！请重新登录", loginId));
        }
        String pass = po.getPassword();
        if(!pass.equals(CommonUtil.encryptStr(password))){
            throw new ServiceException(String.format("您输入的密码：%s不正确！！请重新登录", password));
        }
        if(po.getIsDelete().equals(103002)){
            throw new ServiceException("该用户已被管理员删除，请联系管理员！！！");
        }
        CommonUtil.saveDataToSession(po);
        if("101001".equals(po.getIsVip())){
            return "redirect:/glMain";
        }
        if(po.getUsername().equals(Constant.NEW_USER.getMessage()) && pass.equals(CommonUtil.encryptStr(Constant.INIT_PASSWORD.getMessage()))){
            return "redirect:/initUser";
        }
        return "redirect:/search";
    }

    @GetMapping("logout")
    public String logout(){
        CommonUtil.logout();
        return "redirect:/index";
    }
}
